
import { Component, OnInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { QueryModel } from '../../model/report/query-model';
declare const $: any;
import { DxDropDownBoxComponent } from 'devextreme-angular';

@Component({
    selector: 'app-report-pun',
    templateUrl: './wp.component.html',
    styleUrls: ['./wp.component.scss']
})

export class WPComponent implements OnInit {
    title = 'Working Pace';
    public chartOption: any;

    public items: any[];

    /*生产线 - 班次*/
    public subAreaItems: any[];
    public subAreaSelected: any[];
    public shiftItems: any[];
    public shiftSelected: any;

    @ViewChild('ddda') ddda: DxDropDownBoxComponent;

    constructor(private commServices: CommService) {
    }

    ngOnInit() {
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD HH:mm');
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAreaSelected = [];
    }

    clearSubAreaSelected() {
        this.subAreaSelected = [];
    }
    subAreaSelectedOk() {
        this.ddda.instance.close();
    }
    /**
     * 获取表格数据
     */
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = this.subAreaSelected.map(e => e.subArea);
        queryModel.shift = this.shiftSelected.shiftId;
        this.commServices
            .getList(queryModel, ReportUrls.CTWpListUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    if(queryModel.querySubAreaIds[0].slice(0,2) === 'GF'){
                        model.data.forEach(e => {
                            var sub: string = '';
                            sub = e.subArea.replace(/(^\s*)|(\s*$)/g, "");
                            switch(sub){
                                case 'GFAL1': sub += '_装配主线';  break;
                                case 'GFBU1': sub += '_测试线';  break;
                                case 'GFCL1': sub += '_CASE 机加工线';  break;
                                case 'GFCR1': sub += '_行星齿轮组分装线';  break;
                                case 'GFCS1': sub += '_中间支撑架分装线';  break;
                                case 'GFDH1': sub += '_飞轮盘减震器壳体分装线';  break;
                                case 'GFHL1': sub += '_HOUSING 机加工线';  break;
                                case 'GFTC1': sub += '_壳体分装线';  break;
                                case 'GFTD1': sub += '_中间轴&差速器分装线';  break;
                            }
                            e.subArea = sub;
                        });
                    }
                    this.items = model.data.list;
                    this.chartOption = this.createOption(this.items, model.data);
                }
            });
    }

    getTime(id: any): String {
        return $('#' + id).val();
    }

    /**ECharts图表相关*/
    // tslint:disable-next-line:member-ordering
    chartsMap = new Map<any, any>();
    onChartInit(index: any, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe((event) => this.chartsMap.forEach((v, k) => v.resize()));
    }

    getTarget(subArea: string, type) {
        const a2 = subArea.slice(subArea.length - 5, subArea.length);
        const index = this.targetNames.findIndex(e => a2 === e);
        if (index === -1) {
            return 1000;
        }
        const t = this.targetDatas[index][type];
        return t;
    }

    targetNames = [];
    targetDatas = [];
    createOption(list: any[], mode: any) {

        const x = new Array();
        const z = new Array();
        this.targetNames = mode.names;
        this.targetDatas = mode.targets;

        const data = ['Working Pace', '目标'];

        list.forEach(e => {
            x.push(e.equipment + e.subArea);
        });
        // list.forEach(e => {
        //     z.push(e.equipment);
        // });

        const y = list.map(e => e.wp);

        const series: any[] = [{
            name: 'Working Pace',
            data: y,
            type: 'bar',
            itemStyle: {
                normal: {
                    color: (params) => {
                        if (params.value >= this.getTarget(params.name, 0)) {
                            return '#63B8FF';
                        } else if (params.value >= this.getTarget(params.name, 1)) {
                            return '#92D050';
                        }
                        return '#FFFF00';
                    }
                },
            },
        }];

        this.targetNames.forEach((e, index) => {
            data.push(e + '上限目标');
            data.push(e + '下限目标');
            const barr = new Array();
            const barr1 = new Array();
            for (let i = 0; i < x.length; i++) {
                barr.push(this.targetDatas[index][0]);
                barr1.push(this.targetDatas[index][1]);
            }
            const b = {
                name: e + '上限目标',
                data: barr,
                type: 'line',
                itemStyle: {
                    normal: { color: '#000' },
                },
            };
            const b1 = {
                name: e + '下限目标',
                data: barr1,
                type: 'line',
                itemStyle: {
                    normal: { color: '#000' },
                },
            };
            series.push(b);
            series.push(b1);
        });

        return {
            legend: {
                data: data
            }, tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            }, grid: {
                top: '10%',
                left: '1%',
                right: '5%',
                containLabel: true
            },
            xAxis: [
                {
                    //boundaryGap: true,
                    // offset:-25,
                    type: 'category',
                    data: x,
                    axisLabel: {

                        interval: 0, // 横轴信息全部显示
                        rotate: -30, // -30度角倾斜显示
                        textStyle: {
                            fontSize: 8,
                        }
                    }
                },
                // {
                //     //offset:-5,
                //     position:'bottom',
                //      type: 'category',
                //      data: z,
                //      axisLabel: {

                //          interval: 0, // 横轴信息全部显示
                //          rotate: -30, // -30度角倾斜显示
                //          textStyle: {
                //              fontSize: 8,
                //              color:'#ff0000'
                //          }
                //      }
                //  }
            ],


            yAxis: {
                type: 'value',
                name: '%',
                //min: '50'
            },
            series: series,
            dataZoom: [
                {
                    show: true,
                    start: 0,
                    end: 100
                },
                {
                    type: 'inside',
                    start: 0,
                    end: 100
                },
                {
                    show: true,
                    yAxisIndex: 0,
                    filterMode: 'empty',
                    width: 30,
                    height: '90%',
                    showDataShadow: false,
                    left: '100%'
                }
            ],
        };
    }
    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
